/*
 * Created by Federico Pisarello - SisDev Software (c) 2013 - fpisarello@sisdevsoft.com
 */

var popForm = 'facturacionPop.php';
var popImprimir = 'docsPdf/pdfFacturas.php';
var popNumeracionForm = 'facturacionNumeracionPop.php';
var popAutorizacionForm = 'facturacionAutorizacionPop.php';
var actionForm = 'facturacionAction.php';

var joDataFactura;
var oTable;
var oTableItem;
var oTablePicking;

var oTableSubIvaVtas;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var actionPickingPK = undefined;
var action = undefined;

function $_init()
{	
	var gaiSelected;
	
	$(document).ready(function() {
		oTable = $('#dt_facturas').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bAutoWidth": false,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?accion=searchFacturas",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					            null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null,
					  			null
					  		]
				});
		
    	$('#dt_facturas tbody td img').live( 'click', function () {
    		var nTr = $(this).parents('tr')[0];
    		if (oTable.fnIsOpen(nTr) )
    		{
    			/* This row is already open - close it */
    			this.src = "images/details_open.png";
    			oTable.fnClose( nTr );
    		}
    		else
    		{            
    			/* Open this row */            
    			this.src = "images/details_close.png";            
    			oTable.fnOpen( nTr, fnFormatDetailsFacturas(oTable, nTr), 'details' );        
    		}    
    	});

    	    	
    	/* Click event handler */
    	$('#dt_facturas tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	        	oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$(document).ready(function() {
    	oTablePicking = $('#dt_picking').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bAutoWidth": false,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?accion=searchPicking",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					            null,
					  			null,
					  			null,
					  			null
					  		]
				});
    	    	
    	/* Click event handler */
    	$('#dt_picking tbody tr').live('click', function () {
    		var aData = oTablePicking.fnGetData(this);
    		var iId = aData[0];
    		actionPickingPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPickingPK = undefined;
	        }
	        else {
	        	oTablePicking.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#facturasDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:840, 
		modal: true,
		closeOnEscape: false,
		position : ['center',10],
		dialogClass:'no-close',
		beforeClose: function() { $_ClearFacturasPopForm(); },
		open: function() {
			$('#facturasDialog').css('background-color','#4f4233');
		}
	});
	
	$("#facturasNumeracionDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:480, 
		modal: true,
		closeOnEscape: false,
		resizable: false,
		position : ['center',10],
		dialogClass:'no-close',
		beforeClose: function() { $_ClearFacturasNumeracionPopForm(); },
		open: function() {
			$('#facturasNumeracionDialog').css('background-color','#4f4233');
		}
	});
	
	$("#facturasAutorizacionDialog").dialog({
		autoOpen:false, 
		height:'auto', 
		width:580, 
		modal: true,
		closeOnEscape: false,
		resizable: false,
		position : ['center',10],
		dialogClass:'no-close',
		beforeClose: function() { $_ClearFacturasNumeracionPopForm(); },
		open: function() {
			$('#facturasAutorizacionDialog').css('background-color','#4f4233');
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAgregar").click( function(e) {
		addProxyShow();
    });
		
	$('#btnEliminar').click( function(e) {
		delProxyShow();
	});
	
	$('#btnNumeracion').click( function(e) {
		numeracionProxyShow();
	});
	
	$('#btnImprimir').click( function(e) {
		imprimirProxyShow();
	});
	
	$('#btnAutorizar').click( function(e) {
		autorizacionProxyShow();
	});	
	
	var refreshId = setInterval( function()    
			{
				if($("#facturasDialog").dialog("isOpen") === false && 
						$("#facturasNumeracionDialog").dialog("isOpen") === false &&
						$("#facturasAutorizacionDialog").dialog("isOpen") === false)
					oTablePicking.fnStandingRedraw();    
			}, 5000);

}

function fnFormatDetailsFacturas(oTable, nTr){
	var aData = oTable.fnGetData(nTr);
	var sOut = "";
	var paramData =  "accion=searchFacturasDetalle&idFactura=" + aData[0];
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
        async: false,
		dataType: 'html',
        success: function(strHtml)
                            {
        						sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
        						sOut += strHtml;
        						sOut += '</table>';
                            }
    });
		
	return sOut;
}

function $_initPop()
{
	$("#fecha").attr('disabled','disabled');
	$('#cliente').attr('disabled','disabled');
	
	$("#vto").mask('99/99/9999',{placeholder:" "}).datepicker({
		showOptions: { direction: "up" },
		dateFormat: 'dd/mm/yy',
		changeMonth: true,
		changeYear: true
	});
	
	//Add Click for All Buttons in Pop Form
	$('#btnCerrar').click( function(e) {
		$('#facturasDialog').dialog('close');
	});
	$('#btnGuardar').click( function(e) {
		$('#facturasPopForm').submit();
	});
	
	$('#bonif').change(function() {
		if($('#bonif').val() >= 100 || $('#bonif').val() < 0) {
			$('#bonif').val('');
		}
		var strTableTotales = devuelveTablaTotales(getSumatoriaTotalesBonif(joDataFactura.totales.subtotal), 
													getSumatoriaTotalesBonif(joDataFactura.totales.bonifCliente), 
													getSumatoriaTotalesBonif(joDataFactura.totales.total));
		$('#gridTotalesFac').html(strTableTotales);
	});
	
	var idTipoComprobante;
	var idSucursal;
		
	oTableItem = $('#dt_facturaItems').dataTable( {
					"bJQueryUI": true,
					"sDom": 'lfrtip',
					"bInfo": false,
					"bRetrieve": true,
					"bFilter": false,
					"bPaginate": false,
					"bLengthChange": false,
					"bSearchable":false,
					"bProcessing": false,
					"bAutoWidth": true,
					"bSort": false,
					"aoColumns": [
					              	null,
									null,
									null,
									null,
									null,
									null,
									null
								],
					"aaData": []
				});
	
	$('.dataTables_wrapper').css('min-height', 0);
	
	var d = new Date();
	var month = d.getMonth()+1;
	var day = d.getDate();
	
	//Populo la Fecha y Hora
	$("#fecha").val(((''+day).length<2 ? '0' : '') + day + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + d.getFullYear());
	$('#cliente').val(joDataFactura.header.razonSocial);
			
	$.each(joDataFactura.items, function (index, item) {
		var arrItem = [ 
		               item.codProducto , 
		               item.descripcion,
		               item.cantidad,
		               item.descUnidadMedida,
		               item.precioUnitario,
		               item.bonificacion,
		               item.importe
		             ];
		
		oTableItem.fnAddData(arrItem);
	});
		
	var strTableTotales = devuelveTablaTotales(getSumatoriaTotalesBonif(joDataFactura.totales.subtotal), 
												getSumatoriaTotalesBonif(joDataFactura.totales.bonifCliente), 
												getSumatoriaTotalesBonif(joDataFactura.totales.total));
	$('#gridTotalesFac').append(strTableTotales);
		
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	//Carga Combo Tipo
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getTipoComprobantes', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbTipo').append($('<option selected>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
	        	if(value.idTipoComprobante == idTipoComprobante)
	        		$('#cmbTipo').append($('<option selected>').text(value.descripcion).attr('value', value.idTipoComprobante));
	        	else
	        		$('#cmbTipo').append($('<option>').text(value.descripcion).attr('value', value.idTipoComprobante));
	        });
	    }
	});
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getSucursales', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbSucursal').append($('<option selected>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
	        	if(value.idSucursal == idSucursal)
	        		$('#cmbSucursal').append($('<option selected>').text(value.descripcion).attr('value', value.idSucursal));
	        	else
	        		$('#cmbSucursal').append($('<option>').text(value.descripcion).attr('value', value.idSucursal));
	        });
	    }
	});
}

function devuelveTablaTotales(subTotal, bonifCliente, total)
{
	//Totales
	var sTableTotales = "<table>";
	sTableTotales += "<tr><td>Subtotal</td><td align='right'>"+subTotal+"</td></tr>";
	sTableTotales += "<tr><td>Bonificaci&oacute;n Cliente</td><td align='right'>"+bonifCliente+"</td></tr>";
	sTableTotales += "<tr><td>Subtotal</td><td align='right'>"+(subTotal - bonifCliente)+"</td></tr>";
	var bonifFactura = 0;
	if($('#bonif').val() != "" && parseInt($('#bonif').val()) != 0) {
		$.each(joDataFactura.totales.subtotal, function (index, item) {
			joDataFactura.totales.bonifFactura[index] = (item - joDataFactura.totales.bonifCliente[index]) - ((item - joDataFactura.totales.bonifCliente[index]) / (1 + ($('#bonif').val() / 100)));
			joDataFactura.totales.bonifFactura[index] = joDataFactura.totales.bonifFactura[index];
			bonifFactura += joDataFactura.totales.bonifFactura[index];

			//Calculo Nuevamente las Alicuotas
			joDataFactura.totales.alicuotas[index] = (item - joDataFactura.totales.bonifCliente[index] - joDataFactura.totales.bonifFactura[index]) * (index / 100);
			
			//Calculo nuevamente los Totales
			joDataFactura.totales.total[index] = (item - joDataFactura.totales.bonifCliente[index] - joDataFactura.totales.bonifFactura[index]) + joDataFactura.totales.alicuotas[index]; 
			
		});	
		sTableTotales += "<tr><td>Bonificaci&oacute;n Factura</td><td align='right'>"+(Math.round(bonifFactura * 100) / 100)+"</td></tr>";
		
		total = getSumatoriaTotalesBonif(joDataFactura.totales.total);
	}
	else {
		$.each(joDataFactura.totales.bonifFactura, function (index, item) {
			item = 0;
		});
	}
		
	$.each(joDataFactura.totales.alicuotas, function (alicuota, montoAlicuota) {
		if(montoAlicuota != 0)
			sTableTotales += "<tr><td>IVA "+alicuota+" %</td><td align='right'>"+(Math.round(montoAlicuota * 100) / 100)+"</td></tr>";		
	});
	sTableTotales += "<tr><td>Total</td><td align='right'>"+(Math.round(total * 100) / 100)+"</td></tr>";
	sTableTotales += "</table>";
	
	return sTableTotales;
}

function getSumatoriaTotalesBonif(arrValores)
{
	var resultSum = 0;
	$.each(arrValores, function (index, item) {
		resultSum += item;
	});
	
	return resultSum;
}

function $_initNumeracionPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnNumeracionCerrar').click( function(e) {
		$('#facturasNumeracionDialog').dialog('close');
	});
	
	$('#cmbNumeracionSucursal').empty();
	
	$.ajax({ 
	    url: actionForm, 
	    type:'POST', 
	    data: 'accion=getSucursales', 
	    dataType: 'json', 
	    success: function(json) {
	    	$('#cmbNumeracionSucursal').append($('<option selected>').text('...').attr('value', ''));
	        $.each(json, function(i, value) {
        		$('#cmbNumeracionSucursal').append($('<option>').text(value.descripcion).attr('value', value.idSucursal));
	        });
	    }
	});

	$('#cmbNumeracionSucursal').change(function() {
		$('#tablaNumeracionDoc').empty();
		if($('#cmbNumeracionSucursal').val() != "") {
			$.ajax({ 
			    url: actionForm, 
			    type:'POST', 
			    data: 'accion=getSucursalDocNumeracion&idSucursal='+$(this).val(), 
			    dataType: 'html', 
			    success: function(html) {
			    	$('#tablaNumeracionDoc').html(html);
			    	
			    	$('.numComprobantes').numeric(false);
			    	$('.numComprobantes').change(function() {
			    		if($(this).val().length < 8) {
			    			var nroDoc = "00000000"+$(this).val(); 
			    			$(this).val(nroDoc.substring(nroDoc.length-8));
			    		}
			    		
			    		$.ajax({
			    	        type: 'POST',
			    	        url: actionForm,
			    	        data: 'accion=cambiarNumeracionComprobante&idTipoComprobanteNumero='+$(this).attr('id')+"&numero="+$(this).val(),
			    			dataType: 'json',
			    	        success: function(jsonObj){
			    	            if(jsonObj.status !== 'OK')
			    					$_showMessage('ERR', jsonObj.status, jsonObj.msg);
			    	        }
			    	    });
			    	});			    	
			    }
			});
		}
	});
}

function $_initAutorizacionPop()
{
	//Add Click for All Buttons in Pop Form
	$('#btnAutorizarFacCerrar').click( function(e) {
		$('#facturasAutorizacionDialog').dialog('close');
	});
	$('#btnAutorizarFac').click( function(e) {
		$_autorizarFacturas();
	});
	
	var oTableFacturasAutorizar = $('#dt_facturasAutorizar').dataTable( {
							"bJQueryUI": true,
							"sPaginationType": "two_button",
							"bInfo": false,
							"bLengthChange": false,
							"bProcessing": true,
							"bFilter": false,
							"bScrollInfinite": true,
							"bScrollCollapse": true,
							"bPaginate": false,
							"iDisplayLength": -1,
							"bServerSide": true,
							"sAjaxSource": actionForm + "?accion=cargaFacturasAutorizar",
							"aaSorting": [[ 0, "asc" ]],
							"aoColumns": [
								  			{"bSortable": false},
								  			{"bSortable": false},
								  			{"bSortable": false},
								  			{"bSortable": false}
								  		 ]
					});
}

function numeracionProxyShow()
{
	$('#facturasNumeracionDialog').load(popNumeracionForm).dialog('open');
}

function autorizacionProxyShow()
{
	$('#facturasAutorizacionDialog').load(popAutorizacionForm).dialog('open');
}

function $_autorizarFacturas()
{
	$.blockUI({
		baseZ: 2000,
		timeout: 60000,
		message: '<h1>Autorizando Facturas.<br /></h1><img src="images/loading.gif" width="100px"><h1>Espere por favor...<span id="msgAdicional"></span></h1>', 
    	css: { 
            border: 'none', 
            padding: '15px',
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px',  
            color: '#fff' 
    		} 
    });
	
	setTimeout(function() {
		var anyError = false;
		$('.docAutorizar').each(function(){
			var idFactura = $(this).attr('id');
			var obj = $(this);
			
			if(anyError)
				return false;
			
			if($(this).attr('src') == "") {
				$.ajax({
			        type: 'POST',
			        async: false,
			        cache: false,
			        url: actionForm,
			        data: {
			        		accion: 'autorizarFacturas',
			        		'idFactura': idFactura 
			        	  },
					dataType: 'json',
			        success: function(jsonObj) {
			        	if(jsonObj.status === 'OK'){
			        		obj.attr('src','images/icon_auth_ok.png');
			        		$('#cae'+idFactura).text(jsonObj.cae);
			        		$('#vto'+idFactura).text(jsonObj.vto);
			        		oTable.fnStandingRedraw();
						}
			        	else {
			        		obj.attr('src','images/icon_auth_error.png');
			        		$_showMessage('ERR', 'ERROR', jsonObj.msg);
			        		anyError = true;
			        	}
			        }
				});
			}
		});
	},50);
	
	$.unblockUI();
}
	
function addProxyShow()
{
	if(actionPickingPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione una Orden de Picking de la Grilla');
		return;
	}
	
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	
	var paramData =  "accion=" + iConst.NEW + "&idPicking=" + actionPickingPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataFactura = jsonObj;
        						//Open Pop Dialog
        						$('#facturasDialog').load(popForm).dialog('open');
                            }
        });
}

function $_saveFactura(action)
{	
	$("#btnGuardar").attr('disabled','disabled');
	
	var paramData = 'accion=addFactura&'+ $("#facturasPopForm").serialize() + '&joDataFactura=' + encodeURIComponent(JSON.stringify(joDataFactura));
		
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#facturasDialog').dialog('close');
				oTable.fnStandingRedraw();
				oTablePicking.fnStandingRedraw();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
            $("#btnGuardar").removeAttr('disabled');
        }
    });

return true;
}

function imprimirProxyShow()
{	
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione una Factura de la Grilla');
		return;
	}
	
	var paramData = "idFactura=" + actionPK;
	window.open(popImprimir + '?' + paramData, '_blank');	
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', 'Seleccione una Factura de la Grilla');
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteFacturasDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteFacturasDialog').css('background-color','#4f4233');
			$('#btnConfirmaEliminar').click( function(e) {
				$_del();
			});
			$('#btnSalirEliminar').click( function(e) {
				$('#deleteFacturasDialog').dialog('close');
			})
		}
	});
	$('#deleteFacturasDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'accion=' + action + '&idFactura=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnStandingRedraw();
										oTablePicking.fnStandingRedraw();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteFacturasDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{	
	$('#facturasPopForm').validate({
		submitHandler: function() {
			$_saveFactura(action);
		}, 		
		rules: {
			cmbTipo: {required: true, minlength: 1},
			cmbSucursal: {required: true, minlength: 1}
		},
		messages: {
			cmbTipo: {required: '', minlength: ''},
			cmbSucursal: {required: '', minlength: ''}
		}
	});
}

function $_initSubIvaVtas()
{
	$(document).ready(function() {
		
		$("#filtrosDialog").dialog({
			autoOpen:false, 
			height:'auto', 
			width:270, 
			modal: true,
			closeOnEscape: false,
			position : ['center',10],		
			dialogClass:'no-close',
			open: function() {
				$('#filtrosDialog').css('background-color','#4f4233');
			}
		});
		
		$("#fechaDesde").mask('99/99/9999',{placeholder:" "}).datepicker({
			showOptions: { direction: "up" },
			dateFormat: 'dd/mm/yy',
			changeMonth: true,
			changeYear: true
		});
		
		$("#fechaHasta").mask('99/99/9999',{placeholder:" "}).datepicker({
			showOptions: { direction: "up" },
			dateFormat: 'dd/mm/yy',
			changeMonth: true,
			changeYear: true
		});
		
		$('#btnImprimir').click( function(e) {
			window.open('docsPdf/pdfSubIvaVtas.php?fechaDesde=' + $('#fechaDesde').val() + '&fechaHasta=' + $('#fechaHasta').val(), '_blank');
		});
		
		$('#btnExcel').click( function(e) {
			window.open(actionForm + '?accion=exportarExcelSubIvaVtas&fechaDesde=' + $('#fechaDesde').val() + '&fechaHasta=' + $('#fechaHasta').val(), '_blank');
		});
		
		$('#btnFiltros').click(function(e) {
			$('#filtrosDialog').dialog('open');
		});
		
    	oTableSubIvaVtas = $('#dt_subIvaVtas').dataTable( {
								"bJQueryUI": true,
								"sPaginationType": "two_button",
								"bInfo": false,
								"bLengthChange": false,
								"bProcessing": true,
								"bAutoWidth": false,
								"bServerSide": true,
								"sAjaxSource": actionForm + "?accion=searchSubIvaVtas&emptyTable=true",
								"aoColumns": [
								            null,
								  			null,
								  			null,
								  			null,
								  			null,
								  			null,
								  			null,
								  			null
								  		]
							});
	});
	
	//Event on PopUp
	//Add Click for All Buttons in Search Form
	$("#btnBuscar").click( function(e) {
		oTableSubIvaVtas.fnReloadAjax(actionForm + '?accion=searchSubIvaVtas&fechaDesde=' + $('#fechaDesde').val() + '&fechaHasta=' + $('#fechaHasta').val());
    });
	
	//Add Click for All Buttons in Search Form
	$("#btnCerrar").click( function(e) {
		$('#filtrosDialog').dialog('close');
    });
}

function $_ClearFacturasPopForm()
{	
	$("#facturasDialog").empty();
}

function $_ClearFacturasNumeracionPopForm()
{	
	$("#facturasNumeracionDialog").empty();
}

